<template>
  <div class="signup">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm signin-box"
    >
      <div class="title">
        <img src="/images/logo.png" alt />
        <h3>创建您的MMooc账号</h3>
      </div>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="rePass">
        <el-input v-model="ruleForm.rePass"></el-input>
      </el-form-item>
      <el-form-item class="code" label="验证码" prop="code">
        <el-input maxlength="6" class="input" v-model="ruleForm.code"></el-input>
        <el-button
          @click="sendCode"
          type="primary"
          plain
          :disabled="!canSendCode"
          class="sendCode"
          icon="el-icon-s-promotion"
          circle
        ></el-button>
        <div v-show="!canSendCode" class="codeTimer">再次发送 {{codeTimer}} 秒</div>
      </el-form-item>
      <el-form-item class="submit">
        <el-button
          :loading="loading"
          :plain="true"
          type="primary"
          @click="submitForm('ruleForm')"
        >立即创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { Input, Form, FormItem, Button, Notification } from "element-ui";
import { getCode } from "@/api/common";
import { signUp } from "@/api/student";
export default {
  components: {
    ElInput: Input,
    ElForm: Form,
    ElFormItem: FormItem,
    ElButton: Button
  },
  data() {
    const validateCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      } else if (!value.match(/^[a-zA-Z0-9]{6}$/)) {
        return callback(new Error("验证码为6位字母或数字"));
      }
      return callback();
    };
    const validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      } else if (!value.match(/^[a-zA-Z0-9\u4e00-\u9fa5]{5,10}$/)) {
        callback(new Error("5-10个中文、字母或数字组合"));
      }
      return callback();
    };
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else if (!value.match(/^1[34578]\d{9}$/)) {
        callback(new Error("目前仅支持11位中国大陆手机号"));
      }
      return callback();
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else if (!value.match(/^[a-zA-Z0-9_-]{6,18}$/)) {
        callback(new Error("密码必须为6-18个字母、数字或下划线组合"));
      }
      return callback();
    };
    const validateRePass = (rule, value, callback) => {
      if (value !== this.ruleForm.pass) {
        callback(new Error("两次密码输入不一致"));
      }
      return callback();
    };
    return {
      canSendCode: true,
      codeTimer: 10,
      loading: false,
      ruleForm: {
        phone: "",
        username: "",
        delivery: false,
        pass: "",
        rePass: "",
        code: ""
      },
      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: "blur" }
        ],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        pass: [{ required: true, validator: validatePass, trigger: "blur" }],
        rePass: [
          { required: true, validator: validateRePass, trigger: "blur" }
        ],
        code: [{ required: true, validator: validateCode, trigger: "blur" }]
      }
    };
  },
  methods: {
    sendCode() {
      if (
        !this.ruleForm.phone.match(/^1[34578]\d{9}$/) ||
        !this.ruleForm.username.match(/^[a-zA-Z0-9\u4e00-\u9fa5]{5,10}$/)
      ) {
        Notification.error({
          title: "发送验证码错误",
          message: "请填写正确格式的手机号和用户名"
        });
        return false;
      }
      getCode({
        tel: this.ruleForm.phone,
        username: this.ruleForm.username,
        Identity: "S"
      }).then(res => {
        let data = res.data;
        if (data.status === 200) {
          this.canSendCode = false;
          let _codeTimer = this.codeTimer;
          let timer = setInterval(() => {
            this.codeTimer--;
            if (this.codeTimer < 0) {
              this.canSendCode = true;
              clearInterval(timer);
              this.codeTimer = _codeTimer;
            }
          }, 1000);
          return true;
        } else {
          Notification.error({
            title: "发送验证码错误",
            message: data.result.msg
          });
          return false;
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = new FormData();
          formData.append("username", this.ruleForm.username);
          formData.append("password", this.ruleForm.pass);
          formData.append("repassword", this.ruleForm.rePass);
          formData.append("tel", this.ruleForm.phone);
          formData.append("code", this.ruleForm.code);
          signUp(formData).then(res => {
            if (res.status === 200) {
              const data = res.data;
              if (data.status === 200) {
                Notification.success({
                  title: "注册成功！",
                  message: "稍后将自动登录"
                });
              }
            } else {
              Notification.error({
                title: "错误",
                message: "服务器异常，请稍后再试！"
              });
            }
          });
        } else {
          return false;
        }
      });
    }
  },
  created() {}
};
</script>

<style lang="scss" scoped>
@media screen and (min-width: 1200px) {
  .signup {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    .signin-box {
      border: 1px solid rgba($color: #000000, $alpha: 0.2);
      border-radius: 12px;
      margin: 40px auto;
      width: 580px;
      padding: 20px 80px 20px 20px;
      min-height: 500px;
      .title {
        padding: 20px 0;
        img {
          width: 200px;
        }
        h3 {
          margin: 10px 0 20px 10px;
          font-size: 20px;
        }
      }
      .code {
        .input {
          float: left;
          width: 50%;
        }
        .sendCode {
          float: left;
          margin-left: 25px;
        }
        .codeTimer {
          float: left;
          color: #909399;
          padding-left: 20px;
        }
      }
      .submit {
        text-align: center;
      }
      .city {
        .city-1 {
          float: left;
          width: 230px;
        }
        .city-2 {
          float: left;
          width: 230px;
        }
        .input {
          margin-right: 30px;
        }
      }
    }
  }
}
</style>